package com.smasher.widget.base;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.AsyncDifferConfig;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;

import com.smasher.widget.listener.OnItemClickListener;

public abstract class BaseRecyclerListAdapter<T, VH extends BaseRecyclerViewHolder<T>> extends ListAdapter<T, VH> {

    public static final String TAG = "ListAdapter";

    protected OnItemClickListener mOnItemClickListener;

    protected BaseRecyclerListAdapter(@NonNull DiffUtil.ItemCallback<T> diffCallback) {
        super(diffCallback);
    }

    protected BaseRecyclerListAdapter(@NonNull AsyncDifferConfig<T> config) {
        super(config);
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int type) {
        return onCreateDefineViewHolder(viewGroup, type);
    }

    /**
     * 创建ViewHolder
     *
     * @param viewGroup viewGroup
     * @param type      type
     * @return VH
     */
    public abstract VH onCreateDefineViewHolder(@NonNull ViewGroup viewGroup, int type);


    @Override
    public void onBindViewHolder(@NonNull VH viewHolder, int position) {
        T item = getItem(position);
        if (item == null) {
            Log.i(TAG, "data item is null in position " + position);
            return;
        }
        onBindViewHolderPre(viewHolder, position);
        viewHolder.setOnItemClickListener(mOnItemClickListener);
        viewHolder.setIndex(position);
        viewHolder.setItem(item);
        viewHolder.bindView();
    }


    public View build(@LayoutRes int resource, ViewGroup viewGroup, boolean attachToRoot) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        return inflater.inflate(resource, viewGroup, attachToRoot);
    }

    protected void onBindViewHolderPre(VH viewHolder, int position) {

    }

    public boolean isIndexLegally(int position) {
        return position >= 0 && position < getItemCount();
    }
}